package com.weizai.carshop.handler;


import com.weizai.carshop.common.enumeration.AppHttpCodeEnum;
import com.weizai.carshop.common.exception.BaseException;
import com.weizai.carshop.common.result.ResponseResult;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

// 定义异常处理信息
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        // 统一异常处理 (服务器异常)
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @ExceptionHandler
    public ResponseResult exception(BaseException e) {
        return ResponseResult.errorResult(e.getAppHttpCodeEnum());
    }

    /*
     * 定义sql错误
     * */

    @ExceptionHandler
    public ResponseResult exception(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        // 判断是否为值重复
        // Duplicate entry '小哲不输一郎' for key 'employee.idx_username'
        if(message.contains("Duplicate")) {
            String currentValue = message.split(" ")[2];
            return ResponseResult.errorResult(AppHttpCodeEnum.SQL_ERROR, currentValue + "重复");
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SQL_ERROR);
    }


    // @ExceptionHandler
    // public ResponseResult exception(HttpMessageNotReadableException e) {
    //   return ResponseResult.errorResult(AppHttpCodeEnum.ARGUMENT_ERROR);
    // }

}
